<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
  <%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!doctype html>
<html>
<head>
<base href="<%=basePath%>">
<meta charset="utf-8" http-equiv="content-type" content="text/html">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>发布填写</title>
<style>
a:link {
	text-decoration: none;
	color: #000;
}
a:visited,
a:hover,
a:active {
	text-decoration: none;
}

a{ 
	border:0;
}
body {
	background-color: #EEE;
}
body,td,th {
	font-family: "微软雅黑";
}

</style>
<link href="css/jquery.mobile-1.4.5.min.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/myloading.js"></script> 
<link type="text/css" rel="stylesheet" href="css/myloading.css" /> 
<link rel="stylesheet" type="text/css" href="css/write.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/publish.css">

<script>
$(document).bind('mobileinit',function(){
 $.mobile.changePage.defaults.changeHash = false;
 $.mobile.hashListeningEnabled = false;
 $.mobile.pushStateEnabled = false;
});
</script>
<script src="js/jquery.mobile-1.4.5.min.js" type="text/javascript"></script>

</head>
<body>
<div data-role="page" id="user_page">
  <div data-role="content" class="content">
    <div class="goods_pic" id="goods_pic">
      <ul id="imglistHolder">
     	 <li id="add_photo">
  				<a href="#"></a>
		</li> 
      </ul>

     
     	<div class="address" id="address" style="height:0px">
       <!--  <img src="images/place.png" />
        <span>韶关市-韶关学院南区丁香苑</span> -->
      </div>
      
    </div>

    <div class="list">
      <ul>
        <li>
          <span class="f_w">标题</span>
          <input class="f_w_title" type="text" id="title" placeholder="标题" >
        </li>
        <li class="list_price">
          <span class="f_w">价格</span>
          <input class="f_m" type="text" id="money" placeholder="请填入数字" >
          <span class="f_w">元</span>
        </li>
        <li class="list_price">
          <span class="f_w">原价</span>
          <input class="f_m" type="text" id="originMoney" placeholder="请填入数字" >
          <span class="f_w">元</span>
        </li>
        <li class="more">
          <a href="javascript:void(0)">
            <div class="f_w" >种类</div>
            <span class="f_select">
                <select id="category">
                <c:forEach items="${listCategoryThing}" var="categoryThing" varStatus="stuts">
                <option value="${categoryThing.id}">${categoryThing.name}</option>
                </c:forEach>
                </select>
            </span>
          </a>
        </li>
        
       <%--  <li class="more">
          <a href="javascript:void(0)">
            <div class="f_w" >位置</div>
            <span class="f_select">
                <select id="location">
                <c:forEach items="${listLocation}" var="listLocation" varStatus="stuts">
                <option value="${listLocation.id}">${listLocation.place}</option>
                </c:forEach>
                </select>
            </span>
          </a>
        </li> --%>
       <!--  <li>
          <span class="f_w">号码</span>
          <input class="f_m" type="text" id="phone" placeholder="请输入联系电话" >
        </li> -->
      </ul>
    </div>

    <div class="infor">
      <textarea cols=10 rows=10 id="describle" placeholder="请输入物品详细信息"></textarea>
    </div>
    <div class="publish"><a id="fabu" href="javascript:void(0)"><img src="images/fabu.png" /></a></div>
  </div>
</div>
</body>
<!-- 微信功能接口 -->
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>

/**
 * 调用微信接口
 */
var appId = '${appId}';
var timestamp= '${timestamp}';
var nonceStr='${nonceStr}';
var signature= '${signature}'; 
wx.config({
      debug: false,
      appId: appId,
      timestamp: timestamp,
      nonceStr: nonceStr,
      signature: signature,
      jsApiList: [
        'checkJsApi',
        'onMenuShareTimeline',
		'onMenuShareAppMessage',
		'onMenuShareQQ',
		'onMenuShareWeibo',
		'chooseImage',
		'uploadImage',
		'getLocation'
      ]
  });
  

/**
 * 用于存储相片
 * 用户本地图片id
 * 微信服务器图片id
 * used2云服务器 图片Url
 */
var images = {
	    localId: [],
	    serverId: [],
	    yunUrl :[] 
	  };
//显示选择的图片
function showChooseImage(){
  var len = images.localId.length;
  var ul = $("#imglistHolder");
  //清空
  ul.children("[img]").remove();
  for(var i = len -1 ;i >= 0; i--){
	  var li = "<li img>";
	  li += ' <a href="javascript:void(0)">';
	  li += "<img src='"+images.localId[i]+"' />";
	  li += '</a>';
	  li += '</li>';
	  ul.prepend(li);
  }
}

//提交数据
function updateDate(){
	var yunStr = "";
	for(var i=0;i<images.yunUrl.length;i++){
			yunStr += (images.yunUrl[i] + ',');
		}
	yunStr = yunStr.substring(0,yunStr.length-1);
	$.ajax({
		  type: 'POST',
		  url: 'api/write/checkAndPublish.do',
		  dataType: 'json',
		  data: {
			  categoryId:$("#category").val(),
			  images:yunStr,
			  cost:$("#money").val(),
			  describle:$("#describle").val(),
			  newDegree:'10',
			  num:'1',
			  originalCost:$("#originMoney").val(),
			  outOfTime:'2016-10-1',
			  title:$("#title").val(),
			  phone:'13794683333',//$("#phone").val(),
			  location:1//$("#location").val()
			  },
		  success: function(res){
			//关闭loading窗口
			//closeAjaxLoading();
			if(res.errcode==0){
				changeTip('信息上传成功，正在为你跳转首页...');
				location.href = "api/index.do";
				}else{
					changeTip('信息上传失败,请稍后再试');
					setTimeout(function () { 
						location.href = "api/index.do";
				    }, 3000);
					}
			
			
			  },
			  error:function(){
				//关闭loading窗口
				closeAjaxLoading();
				$.dialog({content:'服务器繁忙，处理失败！'});
				  }
		});
}

//添加图片
$("#add_photo").click(function(){
	wx.chooseImage({
	    count: 9, // 默认9
	    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
	    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
	    success: function (res) {
	    	images.localId = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片 
	    	showChooseImage();
	  	}
	});
	});
var i = 0;
//微信服务器传过来的id
var serverIds ="";
//本地图片长度
var length ;
 function uploadImg(){
	//开启loading窗口
	getAjaxLoading('正在上传图片');
	//重置
	i = 0;
	
	length = images.localId.length; 
	//清空微信服务器传过来的id
	serverIds ="";
	wxupload();
};


/**
 * 上传到微信服务器
 */
function wxupload(){
	wx.uploadImage({
		localId: images.localId[i], // 需要上传的图片的本地ID，由chooseImage接口获得
		isShowProgressTips: 0, // 默认为1，显示进度提示
		success: function (res) {
			var tip = "已上传 "+(i+1)+" 张图片";
			tip += ",共 "+length+" 张";
			//更新提示内容
			changeTip(tip);
			var serverId = res.serverId; // 返回图片的服务器端ID
			serverIds+=res.serverId+",";
			images.serverId.push(serverId);
			
			if(images.serverId.length==length){
				
				serverIds=serverIds.substring(0,serverIds.length-1);
				changeTip("正在处理图片中...");
				 downloadImg(serverIds);
			}else{
				i++;
				wxupload();
			}
		},
		fail:function(res){
			alert('上传失败');
			}
	});

}
function downloadImg(serverIds){
	$.ajax({
	 type: "POST",
	 url: 'api/image/downloadImg.do',
	 data: {serverIds:serverIds},
	 dataType: "json",
	 success: function(res){
		if(res.errcode==0){
			try{
				images.yunUrl = res.data.images;
				if(images.yunUrl.length==0){
					//关闭loading窗口
					closeAjaxLoading();
					//$.dialog({content:'服务器繁忙，处理失败！'});
				}
				else{
					changeTip('图片处理完毕,开始上传二手物品信息');
					updateDate(); 
				}
				}catch(e){
					//关闭loading窗口
					closeAjaxLoading();
					$.dialog({content:'服务器繁忙，上传失败！'});
					}
		}else{
			//关闭loading窗口
			closeAjaxLoading();
			$.dialog({content:res.errmsg});
		}
	 },
	 error: function(){
		//关闭loading窗口
			closeAjaxLoading();
			$.dialog({content:'服务器繁忙，上传失败！'});
	 }
});	
}

//发布按钮
$("#fabu").click(function(){
	//验证数据
	//图片不为空
	if(images.localId.length ==0){
		alert('请最少添加一张图片');
		return ;
		}
	
	if($.trim($("#title").val())==""){
		alert('标题不能为空');
		return ;
		}
	
	if($.trim($("#money").val())==""){
		alert('价格不能为空');
		return ;
		}
	if($.trim($("#originMoney").val())==""){
		alert('原价不能为空');
		return ;
		}
	/* if($.trim($("#phone").val())==""){
		alert('手机号码不能为空');
		return ;
		} */
	
	//最少1分钱的整数
	var regMoney = /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/;
	if(!regMoney.test($("#money").val())){
		alert('价格格式错误');
		return ;
		}
	if(!regMoney.test($("#originMoney").val())){
		alert('原价格式错误');
		return ;
		}
	//11位手机号码
	/* var regPhone =  /^1[34578]\d{9}$/;
	if(!regPhone.test($("#phone").val())){
		alert('必须输入11位手机号码');
		return ;
	} */
	uploadImg();
});
	
	
	 
</script>

</html>